import mongoose, { Document, Schema } from 'mongoose';

export interface ICategory extends Document {
  name: string;
  description: string;
  parent: mongoose.Types.ObjectId | null;
  level: number;
  path: string;
  icon: string;
  image: string;
  isActive: boolean;
  order: number;
  createdAt: Date;
  updatedAt: Date;
}

const CategorySchema: Schema = new Schema(
  {
    name: {
      type: String,
      required: [true, '请输入分类名称'],
      trim: true,
    },
    description: {
      type: String,
      default: '',
    },
    parent: {
      type: Schema.Types.ObjectId,
      ref: 'Category',
      default: null,
    },
    level: {
      type: Number,
      default: 1,
    },
    path: {
      type: String,
      default: '',
    },
    icon: {
      type: String,
      default: '',
    },
    image: {
      type: String,
      default: '',
    },
    isActive: {
      type: Boolean,
      default: true,
    },
    order: {
      type: Number,
      default: 0,
    },
  },
  {
    timestamps: true,
  }
);

// 创建索引
CategorySchema.index({ parent: 1 });
CategorySchema.index({ path: 1 });
CategorySchema.index({ order: 1 });

// 在保存前处理路径
CategorySchema.pre('save', async function (next) {
  // 确保this类型正确
  const category = this as unknown as ICategory & { _id: mongoose.Types.ObjectId };
  
  if (this.isModified('parent') || this.isNew) {
    if (!category.parent) {
      category.level = 1;
      category.path = category._id.toString();
    } else {
      try {
        const parentCategory = await mongoose.model<ICategory>('Category').findById(category.parent);
        if (parentCategory) {
          category.level = (parentCategory as any).level + 1;
          category.path = (parentCategory as any).path + ',' + category._id.toString();
        }
      } catch (error) {
        return next(error as Error);
      }
    }
  }
  next();
});

export default mongoose.model<ICategory>('Category', CategorySchema); 